package com.wuzuqing.android.eightdiagrams.db;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.wuzuqing.android.eightdiagrams.App;

import kotlin.jvm.Synchronized;

/**
 * @CopyRight: 广州仰望星空云科技有限公司
 * @Author : wuzuqing
 * @Email:wuzuqing@xinyu668.com
 * @CreateTime: 24.1.24 1:54 PM
 * @Description: 请写描述
 */
public class DbManager {
    private static DbManager sDbManager = new DbManager();

    private MyDatabase db;


    public static DbManager getInstance() {
        return sDbManager;
    }

    @Synchronized
    public MyDatabase getDb(){
        initDB();
        return db;
    }

    /**
     * 初始化数据库
     */
    public   void initDB() {
        if (db!=null){
            return;
        }
        //本地持久化数据库
        db = Room.databaseBuilder(App.getContext(), MyDatabase.class, "DemoDB")
                //是否允许在主线程上操作数据库，默认false。
                .allowMainThreadQueries()
                //数据库创建和打开的事件会回调到这里，可以再次操作数据库
                .addCallback(new CallBack())
                .build();
    }

    private static final String TAG = "DbManager";
    static class CallBack extends RoomDatabase.Callback {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            Log.d(TAG, "db create");
        }

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            Log.d(TAG, "db open");
        }
    }

}
